#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import json

from app import db
from app.manage.model import Private, Edition
from . import manage, restfulApi
from flask_restful import Resource
from app.public import ResultJson, paginates
from flask import request, jsonify, render_template


@manage.route('/')
def index():
    return render_template('manage/manageIndex.html')


@manage.route('/manageAdd')
def manageadd():
    return render_template('manage/manageAdd.html')


@manage.route('/manageEdit/<int:id>')
def manageedit(id):
    return render_template('manage/manageEdit.html')

class IndexApi(Resource):
    def get(self):
        queryset = Private.query.order_by('id')
        result = ResultJson()  # 实例
        if queryset:
            paginate, page_range = paginates(request, queryset)  # 获取分页
            result.count = paginate.total  # 获取总行数
            for i in paginate.items:
                result.data.append(i.to_json())
        return result.to_json()

    def post(self):

        data = json.loads(str(request.data, 'utf-8'))
        # 将name, position, ctime   重新赋值到字典中, 重新生成版本信息字典
        private = {}
        result = {"code": 10000}  # 创建字典, 默认是成功的
        private['name'] = data.pop('name')
        private['position'] = data.pop('position')
        private['ctime'] = data.pop('ctime')
        if not Private.query.filter_by(name=private['name']).first():
            # 创建版本信息， 只有当项目名称不存在的时候才会添加
            # 需要先添加版本信息， 创建之后才会有ID信息
            instance = Edition(**data)
            db.session.add(instance)
            db.session.commit()
            # 需要先获取到 版本ID, 并且赋值， 否则就不能使用instance
            private['edition_id'] = instance.id
            instance = Private(**private)
            # 添加并提交到数据库
            db.session.add(instance)
            db.session.commit()
        else:
            result["code"] = 10001
        return result


class GetPutDelete(Resource):
    def __init__(self):
        self.result = ResultJson()

    # 只处理数据库
    def change(self, dic, queryset):
        flag = False
        for key, value in dic.items():
            if hasattr(queryset, key):
                setattr(queryset, key, value)
            db.session.commit()
            flag = True
        return flag

    # 单页面的获取数据接口
    def get(self, rid):
        queryset = Private.query.get(rid)
        result = ResultJson()
        # 只有当这个ID存在的时候，才将数据拼到一个字典中
        if queryset:
            getPrivateJson = queryset.to_json()
            getEdition = Edition.query.get(queryset.edition_id)
            getEditionJson = getEdition.to_json()
            getPrivateJson.update(getEditionJson)
            del getPrivateJson["edition_id"]  # 前台渲染不需要这个关连值
            result.code = 10000
            result.data.append(getPrivateJson)
        else:
            result.code = 10001
        return result.to_json()

    # 删除
    def delete(self, rid):
        queryset = Private.query.get(rid)
        # 如果这个ID存在， 先删除版本信息， 然后在删除项目的条目， 然后提交
        if queryset:
            db.session.delete(Edition.query.get(queryset.edition_id))
            db.session.delete(queryset)
            db.session.commit()
            self.result.code = 10000
        return self.result.to_json()

    # 编辑
    def put(self, rid):
        '''
        :param rid:    前台传递的修改值
        :return:   code值   10000  成功  其它都为失败
        '''
        # 获取前台的数据
        data = json.loads(str(request.data, 'utf-8'))
        queryset = Private.query.get(rid)
        if queryset:   # 判断id是否存在
            # 将数据中的 这几个值重新定义， 项目名称字段
            private = {}
            private['name'] = data.pop('name')
            private['position'] = data.pop('position')
            private['ctime'] = data.pop('ctime')
            # 如果数据库修改成功了, 那就继续往下执行
            if self.change(private, queryset):
                queryset = Edition.query.get(queryset.edition_id)
                if self.change(data, queryset):
                    self.result.code = 10000
        return self.result.to_json()




restfulApi.add_resource(IndexApi, '/gpAPi', endpoint="gpApi")
restfulApi.add_resource(GetPutDelete, '/gpdApi/<int:rid>', endpoint='GetPutDelete')
